import React from 'react';

import Header from '../common/Header';
import Validate from '../common/Validate';
import CKModal from '../components/CKModal';
import AMUIReact,{
	Container,
	ButtonGroup,
	Button,
	Input,
	Form,
	Icon,
	Selected,
	Grid,
	Col,
	Popover,
	PopoverTrigger,
	UCheck
} from 'amazeui-react';

import Fetch from '../common/Fetch';
import "../assets/css/manage/blog.less";
class ArticleEdit extends React.Component {
    constructor(props) {
        super(props);

		this.state = {
			data:{
				art_id:null,
				art_title:'',
				art_type:'',
				art_img:'',
				ctg_id:'',
				ctg_name:'',
				art_summary:'',
				art_content:'',
				art_md_content:'',
				art_author:'',
				art_area: this.props.location.query.area ? this.props.location.query.area : '',
			},
			is_upload:false,
			upload_img:'',
			is_save:false,
			type:this.props.params.id ? 'edit':'add',
			init:false,
			is_upload_editor:false,
			upload_img_editor:'',
		};
		this.option_type = [{'value': '1','label':'文字'},{'value':'2','label':'图片'},{'value':'3','label':'连接新闻'}];
		this.option_area = [{'value': '1','label':'编辑区'},{'value':'2','label':'发布区'},{'value':'3','label':'已发布区'}];
		this.user_name = CKLogin.getUser().acc_name;
		this.file = null;
		this.file_deitor = null;
		this.editor = null;
		this.build_work = null;
		this.build_demo_time = null;
		this.build_work_summary = null;
		this.is_author = false;
    }

    componentDidMount() {
		this.initEditor();
    }

	/**
	 * 初始化编辑器
	 */
	initEditor() {
		this.editor = CodeMirror(document.querySelector('#editor'),{
			mode: "markdown",
			theme:'dracula',
			styleActiveLine: true,
			matchBrackets: true,
			lineNumbers: true,
			showCursorWhenSelecting: true,//在选择时是否显示光标，默认为false
		});

		this.editor.on('change',() => {
			clearTimeout(this.build_demo_time);
			this.build_demo_time = setTimeout(()=>{
				this.buildDemo();
				this.buildSummary();
			},1500);
		});
		if(this.state.type == 'edit') {
			this.loadArticleDate();
		}
	}

	/**
	 * 绑定预览
	 */
	buildDemo() {
		if (!this.build_work) {
			this.build_work = new Worker('vendor/works/build_marked.js');
			this.build_work.onmessage = (e)=>{
				$('#markdown_demo').html(e.data);
			};

			this.build_work.onerror = (err)=>{
				$('#markdown_demo').html(err.lineno+':'+err.message);
			};
		}

		this.build_work.postMessage(this.editor.getValue());
	}

	buildSummary() {
		if (!this.build_work_summary) {
			this.build_work_summary = new Worker('vendor/works/build_marked.js');
			this.build_work_summary.onmessage = (e)=>{
				$('#blog_summary').html(e.data);
			};

			this.build_work_summary.onerror = (err)=>{
				$('#blog_summary').html(err.lineno+':'+err.message);
			};
		}
		this.build_work_summary.postMessage(this.editor.doc.getRange({line:0,ch:0},{line:10,ch:0}));
	}

	/**
	 * 获取文章详情
	 * @returns {XML}
	 */
	loadArticleDate() {
		Fetch('/cms/article_manage/get_one_article',{cipher_id: this.props.params.id},(res)=>{
			if (res.status) {
				let data = this.state.data;
				$.map(data, (item, index) => {
					data[index] = res.data[index];
				});
				this.editor.setValue(res.data.art_md_content);
				$('#markdown_demo').html(res.data.art_content);
				this.setState({
					data: data
				});
			} else {
				this.modal.alert('错误','获取文章信息出错！');
			}
		})
	}

	/**
	 * 绑定值
	 * @returns {XML}
	 */
	changeHandler(field){
		return (e)=>{
			let info = this.state.data;
			if(field == 'art_type') {
				info[field] = e;
			} else if(field == 'art_area') {
				info[field] = e;
			} else if (field == 'art_author') {
				this.is_author = true;
				info[field] = e.target.value;
			} else {
				info[field] = e.target.value;
			}
			this.setState({data:info});
		}
	}

	/**
	 * 处理提交数据
	 * @returns {*}
	 */
	checkData() {
		let valid = {
			'art_title':{role:'*2-100',errmsg:'用户名为2到100个字符'},
			'ctg_name':{role:'*',errmsg:'文章分类不能为空'},
			'art_author':{role:'*',errmsg:'文章作者不能为空'},
			'art_type':{role:'*',errmsg:'文章类型不能为空'},
		};

		let data = this.state.data;

		data.art_md_content = this.editor.getValue();
		data.art_content = $('#markdown_demo').html();
		data.art_summary = $('#blog_summary').html();
		if (this.state.type === 'edit') {
			data['art_id'] = this.props.params.id;
		}
		if (this.state.upload_img !== '') {
			data['upload_file'] = this.state.upload_img;
		}
		if (!this.is_author) {
			data['art_author'] = this.user_name;
		}

		try {
			Validate.inst().checkData(data,valid);
			if (this.state.type === 'add' && this.state.upload_img === '') {
				this.modal.alert('错误', '请上传文章封面图片');
				return false;
			}
			return data;
		} catch (e) {
			this.modal.alert('错误',e);
			return false;
		}
	}

	/**
	 * 提交保存
	 */
	save = ()=>{
		let data = this.checkData();
		if (data === false) return;

		if (this.state.is_save) return;
		this.setState({
			is_save:true
		});
		this.modal.load('正在保存文章...');
		Fetch('/cms/article_manage/save',{data:data},(res)=>{
			if (res.status) {
				this.modal.alert('成功','保存文章数据成功!',()=>{
					this.context.router.push('/ArticleManages');
				});
			} else {
				this.modal.alert('失败','保存文章失败!!');
				this.setState({
					is_save:false
				});
			}
		},()=>{
			this.modal.alert('失败','远程调用失败!!');
			this.setState({
				is_save:false
			});
		});
	};

	/**
	 * 更改文本
	 * @param type
	 */
	changeStyle(type) {
		return (e)=>{
			let text = this.editor.getSelection();
			switch (type) {
				case 'bold':
					// text = text.replace(/\*\*/g, "");
					if(!text) {
						this.editor.replaceSelection('** **');
					} else {
						this.editor.replaceSelection('**' + text + '**');
					}
					break;
				case 'italic':
					if(!text) {
						this.editor.replaceSelection('**');
					} else {
						this.editor.replaceSelection('*'+text+'*');
					}
					break;
				case 'image':
					console.log('这里只是一个图片标志');
					break;
			}
		}
	}

	/**
	 * 封面图上传
	 */
	uploadCover = ()=>{
		if (!this.file) {
			let self = this;
			this.file = $('<input type="file"/>');
			this.file.on('change',function(e){
				self.modal.load('正在读取图片...');
				lrz(this.files[0],{width:1000,quality:.9})
					.then((rst)=>{
						$('#art_img').attr('src',rst.base64);
						self.setState({
							is_upload:true
						});
						self.modal.load('正在上传图片...');
						Fetch('/cms/article_manage/upload_img',
							{base:rst.base64},
							(res)=>{
								self.modal.closeModal();
								if (res.status) {
									self.setState({
										is_upload:false,
										upload_img:res.data
									});
								}
							}
						);
					})
					.catch((err)=>{
						self.modal.closeModal('上传图片出错!:'+err);
					}).always(()=>{
					this.file.value = '';
				});
			});
		}
		this.file.click();
	};

	/**
	 * 编辑器上传图片
	 */
	uploadEdit = ()=>{
		if (!this.file_deitor) {
			let self = this;
			this.file_deitor = $('<input type="file"/>');
			this.file_deitor.on('change',function(e){
				self.modal.load('正在读取图片...');
				lrz(this.files[0],{width:600,quality:.9})
					.then((rst)=>{
						self.setState({
							is_upload_editor:true
						});
						self.modal.load('正在上传图片...');
						Fetch('/cms/article_manage/upload_img',{base:rst.base64},(res)=>{
								self.modal.closeModal();
								if (res.status) {
									self.editor.replaceSelection('![]('+ res.data +')');
								}
							}
						);
					})
					.catch((err)=>{
						self.modal.closeModal('上传图片出错!:'+err);
					}).always(()=>{
					this.file_deitor.value = '';
				});
			});
		}
		this.file_deitor.click();
	};

	/**
	 * 选择文章分类
	 */
	selectCategory = ()=> {
		this.modal.view('分类选择', 'category', {}, (res)=> {
			var data = this.state.data;
			data['ctg_id'] = res['ctg_id'];
			data['ctg_name'] = res['ctg_name'];
			this.setState({
				data: data,
			});
		});
	};

	/**
	 * 设置编辑器自动换行
	 * @param e
	 */
	warpHandler = (e)=>{
		this.editor.setOption('lineWrapping',e.currentTarget.checked);
	};

	render() {
		let data = this.state.data;
		return (
			<div className="content">
				<Header title={this.state.type === 'edit'?'修改文章':'添加文章'} back={true}/>
				<div className="content_main">
					<div style={{marginBottom:'20px'}}>
						<h4 className="title">文章信息</h4>
					</div>
					<Grid className="fixed-max-width">
						<Col lg={1}></Col>
						<Col lg={6} lgOffset={5} style={{textAlign:"right"}}>
							<Button
								amStyle="primary"
								onClick={this.save}
								disabled={this.state.is_save}>
								{this.state.is_save?'保存中...':'保存文章'}
							</Button>
						</Col>
					</Grid>
					<Container className="fixed-max-width">
						<Grid className="doc-g">
							<Col lg={12}>
								<Input label="文章标题"
									   value={data.art_title || ''}
									   placeholder="文章标题2-100个字符"
									   onChange={this.changeHandler('art_title')}
								/>
							</Col>
						</Grid>
						<Grid className="doc-g">
							<Col lg={3}>
								<Input label="文章分类"
									   ref="ctg_name"
									   value={data.ctg_name || ''}
									   placeholder="文章分类"
									   disabled
									   btnAfter={<Button onClick={this.selectCategory}>选择分类</Button>}
								/>
							</Col>
							<Col lg={3}>
								<Input label="文章作者"
									   ref="art_author"
									   value={data.art_author || this.user_name}
									   placeholder="文章作者"
									   onChange={this.changeHandler('art_author')}
								/>
							</Col>
							<Col lg={3}>
								<div className="am-form-group">
									<label className="am-form-label">文章所属区</label>
									<Selected className="fixed-select-width"
											  btnStyle="success"
											  placeholder="请选择文章所属区"
											  data={this.option_area}
											  onChange={this.changeHandler('art_area')}
											  value={data.art_area}/>
								</div>
							</Col>
							<Col lg={3}>
								<div className="am-form-group">
									<label className="am-form-label">文章类型</label>
									<Selected className="fixed-select-width"
											  btnStyle="success"
											  placeholder="请选择文章类型"
											  data={this.option_type}
											  onChange={this.changeHandler('art_type')}
											  value={data.art_type || ''}/>
								</div>
							</Col>
						</Grid>
						<Grid className="doc-g">
							<Col lg={6}>
								<div className="am-form-group">
									<label className="am-form-label">封面图片</label>
									<p>
										<div style={{width:"50%"}} className="am-u-sm-4 am-u-end">
											<img
												style={{maxWidth: "100%"}} id="art_img"
												src={data.art_img || require('../assets/img/default_head.jpg')}
												className="header_img"/>
											<Button style={{marginLeft:'20px'}}
													amStyle="primary"
													disabled={this.state.is_upload}
													onClick={this.uploadCover}>

												{this.state.is_upload ? '上传中...' : '上传'}
											</Button>
										</div>
									</p>
								</div>
							</Col>
						</Grid>
						<div style={{marginTop:'20px'}}></div>
						<div className="am-form-group">
							<label className="am-form-label">文章简介</label>
							<span> (默认取文章内容10行转为HTML显示，注意不要在前10行放代码块)</span>
							<div id="blog_summary"
								 style={{height:"auto"}}
								 dangerouslySetInnerHTML={{__html:data.art_summary || ''}}
								 className="markdown_content markdown-body">
							</div>
						</div>
					</Container>
					<Grid>
						<Col sm={6}>
							<div>
								<label className="am-form-label">编辑文章内容 (Markdown)</label>
							</div>
							<ButtonGroup>
								<PopoverTrigger
									amSize="sm" // 设置 popover 大小
									placement="top"
									popover={<Popover>加粗</Popover>}>
									<Button amSize="xs" onClick={this.changeStyle('bold')}>
										<Icon icon="bold"/>
									</Button>
								</PopoverTrigger>
								<PopoverTrigger
									amSize="sm" // 设置 popover 大小
									placement="top"
									popover={<Popover>加斜</Popover>}>
									<Button amSize="xs" onClick={this.changeStyle('italic')}>
										<Icon icon="italic"/>
									</Button>
								</PopoverTrigger>
								<PopoverTrigger
									amSize="sm" // 设置 popover 大小
									placement="top"
									popover={<Popover>图片</Popover>}>
									<Button amSize="xs" onClick={this.uploadEdit}>
										<Icon icon="file-image-o"/>
									</Button>
								</PopoverTrigger>

							</ButtonGroup>
							<Input type="checkbox" label="自动换行"
								   labelClassName="am-fr"
								   onChange={this.warpHandler} inline/>
							<div id="editor"></div>
						</Col>
						<Col sm={6}>
							<label className="am-form-label">预览</label>
							<div id="markdown_demo" className="markdown_content markdown-body"></div>
						</Col>
					</Grid>
				</div>
				<CKModal ref={(c)=>{this.modal = c}}/>
			</div>
		);
    }
}

ArticleEdit.contextTypes = {
	router: React.PropTypes.object
};

export default ArticleEdit;